import React, { useState, useEffect, useMemo } from 'react'
import PageHeader from '../components/PageHeader'
import { getAppointList, appointmentUpdate } from '../utils/api'
import { List, Card, Space, Tag, Button, DatePicker, Toast, Dialog, Tabs, ErrorBlock } from 'antd-mobile'
import { dateFmt } from '../utils/util'
import { wapper } from '../utils/hoc'


const Appoint: React.FC = () => {
  const { role_id } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}')
  const [status, setStatus] = useState<string | number>(1)
  const [currentId, setCurrentId] = useState(0)
  // 控制日期选择器的显示状态太
  const [visible, setVisible] = useState(false)
  const [appointList, setAppointList] = useState<AppointRowType[]>([])
  // 请求预约列表
  const getAppoint = async () => {
    const { id, role_id } = JSON.parse(localStorage.getItem('userLoginInfo') || '{}')
    const params: { doctorid?: number, patientid?: number } = {}
    // 医生
    if (role_id === 1) {
      params.doctorid = id
    } else if (role_id === 2) {    // 患者
      params.patientid = id
    }
    const { data } = await getAppointList(params)
    if (data.code === 200) {
      setAppointList(data.data)
    }
  }
  useEffect(() => {
    // 请求预约数据
    getAppoint()
  }, [])
  // 计算预约状态
  const getStatusLabel = (status: number) => {
    switch (status) {
      case -1:
        return <Tag color="danger">已取消</Tag>
      case 1:
        return <Tag color="success">未就诊</Tag>
      case 2:
        return <Tag color="primary">已就诊</Tag>
      default:
        return <Tag>无效状态</Tag>
    }
  }
  // 预约id
  const showDatePicker = (id: number) => {
    setVisible(true)
    // 记录当前需要更新的预约信息
    setCurrentId(id)
  }
  const submit = async (date: Date) => {
    setVisible(false)
    const appoint_time = date.getTime()
    const { data } = await appointmentUpdate({ id: currentId, appoint_time })
    if (data.code === 200) {
      Toast.show({ icon: 'success', content: data.msg })
      // 更新预约列表数据
      getAppoint()
      return
    }
    Toast.show({ icon: 'fail', content: data.msg })
  }
  const appointUpdate = async (option: { id: number, status: number }) => {
    const res = await Dialog.confirm({ content: '确认当前操作?' })
    if (res) {
      const { id, status } = option
      const { data } = await appointmentUpdate({ id, status })
      if (data.code === 200) {
        Toast.show({ icon: 'success', content: data.msg })
        // 请求最新的预约列表数据
        getAppoint()
        return
      }
      Toast.show({ icon: 'fail', content: data.msg })
    }

  }
  const tabsConfig = [
    { key: 1, title: '未就诊' },
    { key: 2, title: '已就诊' },
    { key: -1, title: '已取消' },
  ]
  // 筛选当前标签页对应的预约预约数据
  const currentAppointList: Array<AppointRowType> = useMemo(() => {
    const result = appointList.filter(item => item.status == status)
    return result
  }, [status, appointList])
  return (
    <div>
      <PageHeader>
        <h4>预约管理</h4>
      </PageHeader>
      <Tabs onChange={key => setStatus(key)}>
        {
          tabsConfig.map(item => (
            <Tabs.Tab title={item.title} key={item.key}>
              <List>
                {currentAppointList.map((item: AppointRowType) => (
                  <List.Item key={item.id}>
                    <Card title={item.name}>
                      <Space direction="vertical">
                        <div>预约时间:{dateFmt(item.appoint_time)}</div>
                        {/* role_id:1-医生 2-患者 */}
                        {
                          role_id === 1 ?
                            <>
                              <div>患者姓名:{item.name}</div>
                              <div style={{ marginTop: 8 }}>患者电话:
                                <a href={`tel:${item.phone}`}>{item.phone}</a>
                              </div>
                            </>
                            :
                            <>
                              <div>医生姓名:{item.doctor}</div>
                              <div style={{ marginTop: 8 }}>医生电话:
                                <a href={`tel:${item.phone}`}>{item.doctorPhone}</a>
                              </div>
                            </>
                        }

                        <div>预约状态:{getStatusLabel(item.status)}</div>
                        {
                          item.status === 1 ? <Space justify="end">
                            {/* status=2  已就诊 */}
                            <Button onClick={() => appointUpdate({ id: item.id, status: 2 })} size="mini" shape="rounded" color="primary">已就诊</Button>
                            <Button onClick={() => showDatePicker(item.id)} size="mini" shape="rounded" color="success">更新预约时间</Button>
                            {/* status=-1  已取消 */}
                            <Button onClick={() => appointUpdate({ id: item.id, status: -1 })} size="mini" color="danger" shape="rounded">取消预约</Button>
                          </Space> : ''
                        }
                      </Space>
                    </Card>
                  </List.Item>
                ))}
              </List>
              {/* 无数据提示 */}
              {currentAppointList.length === 0 ? <ErrorBlock status="empty" /> : ''}
            </Tabs.Tab>
          ))
        }
      </Tabs>


      <DatePicker
        visible={visible}
        precision='minute'
        onConfirm={submit}
        onClose={() => {
          setVisible(false)
        }}
      />
    </div>
  )
}

export default wapper(Appoint,{title:'立即预约',requireLogin:true})
